package com.lc.service.impl;

import com.cnpc.framework.base.entity.BaseResponse;
import com.cnpc.framework.base.entity.SysFile;
import com.cnpc.framework.base.service.impl.BaseServiceImpl;
import com.cnpc.framework.utils.DateUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.lc.service.UtilService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.*;

@Service
public class UtilServiceImpl extends BaseServiceImpl implements UtilService {
    public BaseResponse setUserInfo(String userId, Object obj, String exColumn) throws Exception {
        BaseResponse response = new BaseResponse();
        String column = "";
        if (StringUtils.isNotEmpty(exColumn)) {
            column = "," + exColumn;
        } else {
            column = "";
        }
        String sql = "select u.id,u.name,o.id orgId,o.name orgName" + column +
                " from tbl_user u left join tbl_org o on o.id = u.dept_id where u.id=:userID";
        Map<String, Object> params = new HashMap<>();
        params.put("userID", userId);
        Map<String, Object> user = getMapBySql(sql, params);

        if (user == null) {
            response.setStatus(2);
            response.setMessage("人员不存在!");
            return response;
        }
        Class<?> cls = obj.getClass();
        Field userName = cls.getDeclaredField("userName");
        Field orgId = cls.getDeclaredField("deptId");
        Field orgName = cls.getDeclaredField("deptName");

        userName.setAccessible(true);
        userName.set(obj, user.get("name") == null ? null : user.get("name").toString());
        orgId.setAccessible(true);
        orgId.set(obj, user.get("orgID") == null ? null : user.get("orgID").toString());
        orgName.setAccessible(true);
        orgName.set(obj, user.get("orgName") == null ? null : user.get("orgName").toString());
        if (StringUtils.isNotEmpty(exColumn)) {
            Field exField = cls.getDeclaredField(exColumn);
            exField.setAccessible(true);
            exField.set(obj, user.get(exColumn) == null ? null : user.get(exColumn).toString());
        }
        return response;
    }

    @Override
    public BaseResponse setDevInfo(String devId, Object obj) throws Exception {
        BaseResponse response = new BaseResponse();
        String devSql = "select d.devCode,d.devName,d.devType,d.devStyle,d.devModel,d.assetValue from t_device d where d.id=:devID";
        Map<String, Object> devParams = new HashMap<>();
        devParams.put("devID", devId);
        Map<String, Object> dev = getMapBySql(devSql, devParams);
        if (dev == null) {
            response.setStatus(2);
            response.setMessage("设备不存在!");
            return response;
        }
        Class<?> cls = obj.getClass();
        Field devCode = cls.getDeclaredField("devCode");
        Field devName = cls.getDeclaredField("devName");
        Field devType = cls.getDeclaredField("devType");
        Field devStyle = cls.getDeclaredField("devStyle");
        Field devModel = cls.getDeclaredField("devModel");
        Field price = null;
        try{
            price = cls.getDeclaredField("price");
        }catch (Exception e){

        }

        devCode.setAccessible(true);
        devCode.set(obj,dev.get("devCode") == null ? null : dev.get("devCode").toString());
        devName.setAccessible(true);
        devName.set(obj,dev.get("devName") == null ? null : dev.get("devName").toString());
        devType.setAccessible(true);
        devType.set(obj,dev.get("devType") == null ? null : dev.get("devType").toString());
        devStyle.setAccessible(true);
        devStyle.set(obj,dev.get("devStyle") == null ? null : dev.get("devStyle").toString());
        devModel.setAccessible(true);
        devModel.set(obj,dev.get("devModel") == null ? null : dev.get("devModel").toString());

        if (price != null) {
            price.setAccessible(true);
            price.set(obj,dev.get("assetValue") == null ? null : Double.parseDouble(dev.get("assetValue").toString()));
        }

        response.setStatus(1);
        return response;
    }

    @Override
    public SysFile uploadFile(MultipartFile file, String userId, String type, HttpServletRequest request) {
        String filePrefixFormat = "yyyyMMddHHmmssS";
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String savedName = DateUtil.format(new Date(), filePrefixFormat) + "_" + uuid + originalFilename.substring(index);
        String base = request.getSession().getServletContext().getRealPath("/");
        String dir = getUploadPath(type);
        String path = base + dir + savedName;

        File filepath = new File(path);
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文件当中
        File realFile = new File(path);
        try {
            file.transferTo(realFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SysFile sysFile = new SysFile();
        sysFile.setFileName(originalFilename);
        sysFile.setSavedName(savedName);
        sysFile.setCreateDateTime(new Date());
        sysFile.setUpdateDateTime(new Date());
        sysFile.setFilePath(dir + savedName);
        sysFile.setCreateUserId(userId);
        sysFile.setDeleted(0);
        sysFile.setType(type);
        sysFile.setFileSize(realFile.length());
        baseDao.save(sysFile);
        return sysFile;
    }

    @Override
    public List<String> getOrgIdsOfOrgAndBellow(String userId, String orgId) throws Exception {
        String sql = "select levelCode from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        String levelCode = getBySql(sql, param);
        if (StringUtils.isNotEmpty(levelCode)) {
            sql = "select id from tbl_org where levelCode like '" + levelCode + "%'";
            List<String> ids = findBySql(sql, null);
            ids.add(0, levelCode);
            return ids;
        }
        return null;
    }


    @Override
    public String getOrgIdsBellow(String userId, String orgId) throws Exception {
        String sql = "select levelCode from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        String levelCode = getBySql(sql, param);
        if (StringUtils.isNotEmpty(levelCode)) {
            sql = "select GROUP_CONCAT(CONCAT(\"'\",id,\"'\")) from tbl_org where levelCode like '" + levelCode + "%'";
            String ids = getBySql(sql);
            return ids;
        }
        return null;
    }

    public String getUploadPath(String type) {
        String path;
        if ("ft_suggest".equals(type)) {
            path = PropertiesUtil.getValue("suggestPath");
        } else if ("ft_avatar".equals(type)) {
            path = PropertiesUtil.getValue("avatarPath");
        } else {
            path = PropertiesUtil.getValue("uploaderPath");
        }

        return path;
    }

    @Override
    public List<String> getOrgIds(String userId, String orgId) throws Exception {
        /*String sql = "select levelCode, from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        String levelCode = getBySql(sql, param);
        if (StringUtils.isNotEmpty(levelCode)) {
            if (levelCode.length()>=30) {
                String tem = new String(levelCode);
                StringBuilder sb = new StringBuilder();
                sb.append("('").append(tem).append("',");
                while (tem.length()>24) {
                    tem = tem.substring(0,tem.length()-6);
                    sb.append("'").append(tem).append("',");
                }
                sb.deleteCharAt(sb.length()-1).append(")");
                sql = "select id from tbl_org where levelCode in" + sb.toString();
                List<String> ids = findBySql(sql);
                return ids;
            }else {
                sql = "select id from tbl_org where levelCode like '" + levelCode + "%'";
                List<String> ids = findBySql(sql);
                return ids;
            }
        }
        return null;*/

        String sql = "select levelCode,org_type from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode,org_type from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        Map<String, Object> org = getMapBySql(sql, param);

        if (org != null) {
            String levelCode = org.get("levelCode").toString();
            String org_type = org.get("org_type").toString();
            if ("5".equals(org_type)) {
                String tem = new String(levelCode);
                StringBuilder sb = new StringBuilder();
                sb.append("('").append(tem).append("',");
                tem = tem.substring(0, tem.length() - 6);
                sb.append("'").append(tem).append("',");
                sb.deleteCharAt(sb.length() - 1).append(")");
                sql = "select id from tbl_org where levelCode in" + sb.toString();
                List<String> ids = findBySql(sql);
                return ids;
            } else {
                sql = "select id from tbl_org where levelCode like '" + levelCode + "%'";
                List<String> ids = findBySql(sql);
                return ids;
            }
        }
        return null;
    }

    @Override
    public String getOrgIdsStr(String userId, String orgId) throws Exception {
       /* String sql = "select levelCode from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        String levelCode = getBySql(sql, param);
        if (StringUtils.isNotEmpty(levelCode)) {
            if (levelCode.length() >= 30) {
                String tem = new String(levelCode);
                StringBuilder sb = new StringBuilder();
                sb.append("('").append(tem).append("',");
                while (tem.length() > 24) {
                    tem = tem.substring(0, tem.length() - 6);
                    sb.append("'").append(tem).append("',");
                }
                sb.deleteCharAt(sb.length() - 1).append(")");
                sql = "select GROUP_CONCAT(CONCAT(\"'\",id,\"'\")) from tbl_org where levelCode in" + sb.toString();
                String ids = getBySql(sql);
                return ids;
            } else {
                sql = "select GROUP_CONCAT(CONCAT(\"'\",id,\"'\")) from tbl_org where levelCode like '" + levelCode + "%'";
                String ids = getBySql(sql);
                return ids;
            }
        }
        return null;*/
        String sql = "select levelCode,org_type from tbl_org where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", orgId);
        if (StringUtils.isEmpty(orgId)) {
            sql = "select o.levelCode,org_type from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
            param.put("id", userId);
        }
        Map<String, Object> org = getMapBySql(sql, param);

        if (org != null) {
            String levelCode = org.get("levelCode").toString();
            String org_type = org.get("org_type").toString();
            if ("5".equals(org_type)) {
                String tem = new String(levelCode);
                StringBuilder sb = new StringBuilder();
                sb.append("('").append(tem).append("',");
                tem = tem.substring(0, tem.length() - 6);
                sb.append("'").append(tem).append("',");

                sb.deleteCharAt(sb.length() - 1).append(")");
                sql = "select GROUP_CONCAT(CONCAT(\"'\",id,\"'\")) from tbl_org where levelCode in" + sb.toString();
                String ids = getBySql(sql);
                return ids;
            } else {
                sql = "select GROUP_CONCAT(CONCAT(\"'\",id,\"'\")) from tbl_org where levelCode like '" + levelCode + "%'";
                String ids = getBySql(sql);
                return ids;
            }
        }
        return null;
    }

    @Override
    public List<String> getOrgIds1(String userId) throws Exception {
        String sql = "select o.levelCode,org_type from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", userId);

        Map<String, Object> org = getMapBySql(sql, param);
        if (org != null) {
            String levelCode = org.get("levelCode").toString();
            String org_type = org.get("org_type").toString();
            if ("5".equals(org_type)) {
                return null;
            } else {
                sql = "select id from tbl_org where levelCode like '" + levelCode + "%'";
                List<String> ids = findBySql(sql);
                return ids;
            }
        }
        return null;
    }

    @Override
    public List<String> getOrgIds2(String userId,String orgId) throws Exception {
        String sql = "select o.levelCode,org_type from tbl_org o  left join tbl_user u on u.dept_id = o.id where u.id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", userId);
        if (StringUtils.isNotEmpty(orgId)) {
            sql = "select o.levelCode,org_type from tbl_org o  where o.id =:id";
            param.put("id", orgId);
        }

        Map<String, Object> org = getMapBySql(sql, param);
        if (org != null) {
            String levelCode = org.get("levelCode").toString();
            String org_type = org.get("org_type").toString();
            if ("5".equals(org_type)) {
                return null;
            } else {
                sql = "select id from tbl_org where levelCode like '" + levelCode + "%'";
                List<String> ids = findBySql(sql);
                return ids;
            }
        }
        return null;
    }
    @Override
    public String getQrCode(String data, String prefix, String basePath) throws Exception {

        String dirPath = PropertiesUtil.getValue("imgPath.qrCode");
        String realPath = basePath + dirPath;
        File fileDir = new File(realPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        int width = 200; // 图像宽度
        int height = 200; // 图像高度
        String format = "png";// 图像类型
        String filename = prefix+DateUtil.format(new Date(),"yyyyMMddHHmmss")+"."+format;
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(data,
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        //BufferedImage image = toBufferedImage(bitMatrix);
        Path path = FileSystems.getDefault().getPath(realPath, filename);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像

        System.out.println("输出成功.");

        String imageUrl = dirPath + filename;
        return imageUrl;
    }


    @Override
    public SysFile uploadFile(MultipartFile file, String base, String dir, String userId, String type) {
        String filePrefixFormat = "yyyyMMddHHmmssS";
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String savedName = DateUtil.format(new Date(), filePrefixFormat) + "_" + uuid + originalFilename.substring(index);
        String path = base + dir + savedName;

        File filepath = new File(path);
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文件当中
        File realFile = new File(path);
        try {
            file.transferTo(realFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SysFile sysFile = new SysFile();
        sysFile.setFileName(originalFilename);
        sysFile.setSavedName(savedName);
        sysFile.setCreateDateTime(new Date());
        sysFile.setUpdateDateTime(new Date());
        sysFile.setFilePath(dir + savedName);
        sysFile.setCreateUserId(userId);
        sysFile.setDeleted(0);
        sysFile.setType(type);
        sysFile.setFileSize(realFile.length());
        baseDao.save(sysFile);
        return sysFile;
    }

    @Override
    public SysFile uploadFile(MultipartFile file, String base, String dir, String userId, String type, String docName, String docType, String remark, String devID) {
        SysFile sysFile = uploadFile(file , base , dir , userId , type);
        if (StringUtils.isNotEmpty(docName)) {
            sysFile.setFileName(docName);
        }
        sysFile.setFormId(devID);
        sysFile.setRemark(remark);
        sysFile.setType(docType);
        baseDao.save(sysFile);
        return sysFile;
    }

}
